import fs from "fs";
import path from "path";

import pkg from "./package.json";

const node_modules = "./node_modules";
const public_path = "./public";

const pkg_modules = Object.keys(pkg.dependencies);
const dist_dirs = ["dist", "cjs", "amd", "umd", "iife", "esm"];

const indexHTMLPath = "./index.html";
const indexHTML = fs.readFileSync(indexHTMLPath).toString();

let copyDir = (src: string, dst: string) => {
  if (dst.endsWith(path.sep)) {
    dst = path.join(dst, path.basename(src));
  }
  fs.stat(src, (err, stats) => {
    if (err) {
      throw err;
    }
    if (stats.isFile()) {
      fs.copyFile(src, dst, () => {});
    } else if (stats.isDirectory()) {
      if (!fs.existsSync(dst)) {
        fs.mkdirSync(dst);
      }
      fs.readdir(src, (err, files) => {
        files.forEach((file) => {
          copyDir(path.join(src, file), path.join(dst, file));
        });
      });
    }
  });
};

let copyModules = () => {
  fs.readdir(node_modules, (err, modules) => {
    if (err) {
      throw err;
    }
    modules
      .filter((module) => pkg_modules.includes(module))
      .forEach((module) => {
        fs.readdir(path.join(node_modules, module), (err, dirs) => {
          if (err) {
            throw err;
          }
          if (!fs.existsSync(path.join(public_path, module))) {
            fs.mkdirSync(path.join(public_path, module));
          }
          dirs
            .filter((dir) => dist_dirs.includes(dir))
            .forEach((dir) => {
              copyDir(
                path.join(node_modules, module, dir),
                path.join(public_path, node_modules, module, dir)
              );
            });
        });
      });
  });
  console.log(pkg_modules);
};

let createIndexes = (pathname: string) => {
  fs.readdir(path.join(public_path, pathname), (err, files) => {
    if (err) {
      throw err;
    }
    let list = pathname == "/" ? "" : `<li><a href="../">../</a></li>`;
    files
      .filter((file) => file != "index.html")
      .forEach((file) => {
        if (fs.statSync(path.join(public_path, pathname, file)).isDirectory()) {
          createIndexes(path.join(pathname, file));
          file += "/";
        }

        list += `<li><a href="./${file}">${file}</a></li>`;
      });

    fs.writeFile(
      path.join(public_path, pathname, "index.html"),
      indexHTML.replace("#title", pathname).replace("#list", list),
      () => {}
    );
  });
};

(() => {
  createIndexes("/");
})();
